Agent#valid?: Rescue Liquid::Error and save it in errors.

Calling valid? should not raise any exception in general, and in our
case it is undesirable for a syntactically wrong Liquid template in
options to cause Internal Server Error in validation.

Akinori MUSHA 10 years ago
parent
commit
3e0741d100
2 changed files with 27 additions and 0 deletions
  1. 7 0
      app/concerns/liquid_interpolatable.rb
  2. 20 0
      spec/concerns/liquid_interpolatable_spec.rb

+ 7 - 0
app/concerns/liquid_interpolatable.rb

@@ -1,6 +1,13 @@
1 1
 module LiquidInterpolatable
2 2
   extend ActiveSupport::Concern
3 3
 
4
+  def valid?(context = nil)
5
+    super
6
+  rescue Liquid::Error => e
7
+    errors.add(:base, e.message)
8
+    false
9
+  end
10
+
4 11
   def interpolate_options(options, event = {})
5 12
     case options
6 13
       when String

+ 20 - 0
spec/concerns/liquid_interpolatable_spec.rb

@@ -12,4 +12,24 @@ describe LiquidInterpolatable::Filters do
12 12
       @filter.uri_escape('abc:/?=').should == 'abc%3A%2F%3F%3D'
13 13
     end
14 14
   end
15
+
16
+  describe 'validations' do
17
+    class Agents::InterpolatableAgent < Agent
18
+      include LiquidInterpolatable
19
+
20
+      def check
21
+        create_event :payload => {}
22
+      end
23
+
24
+      def validate_options
25
+        interpolated['foo']
26
+      end
27
+    end
28
+
29
+    it "should finish without raising an exception" do
30
+      agent = Agents::InterpolatableAgent.new(name: "test", options: { 'foo' => '{{bar}' })
31
+      agent.valid?.should == false
32
+      agent.errors[:base].first.should =~ /not properly terminated/
33
+    end
34
+  end
15 35
 end